﻿using System;
using System.Drawing;
using System.IO;

namespace com.fukefu.ocr
{
    public class _51MyOCR
    {
        string[] bz = "24|49|19|31|37|27|33|25".Split('|');
        int[] a = new int[] { 0, 8, 9, 6, 5, 4, 3, 2, 1, 7 };
        int[] b = new int[] { 249, 236, 227, 125, 97, 25, 68, 192, 6, 2 };
        int[] biaozhun;
        //初始化
        public _51MyOCR()
        {
            biaozhun = new int[bz.Length];
            for (int j = 0; j < bz.Length; j++)
            {
                biaozhun[j] = int.Parse(bz[j]) - 1;
            }
        }
        public string OCR(Stream stream)
        {
            return OCR(stream, 221, 2);
        }
        public string OCR(Bitmap bt)
        {
            return OCR(bt, 221, 2);
        }
        private string OCR(Bitmap bt, int num, int pianyi)
        {
            int h = bt.Size.Height;
            int w = bt.Size.Width;
            int block = w / 4;
            string result = "";
            for (int i = pianyi; i < w; i += block)
            {
                string str = "";
                for (int j = 0; j < bz.Length; j++)
                {
                    str += bt.GetPixel(i + biaozhun[j] % 6, biaozhun[j] / 6).R == num ? "0" : "1";
                }
                result += CheckOneNum(str);
            }
            return result;
        }
        private string OCR(Stream stream, int num, int pianyi)
        {
            return OCR(new Bitmap(stream), num, pianyi);
        }
        private string CheckOneNum(string str)
        {
            int num = Convert.ToInt32(str, 2);
            for (int j = 0; j < b.Length; j++)
            {
                if ((num & b[j]) == b[j])
                {
                    return a[j].ToString();
                }
            }
            return "";
        }
    }
}
